<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h2>数据总览</h2>
    </div>
    <div class="stats-grid">
      <!-- 3D Stat Cards -->
      <div class="stat-card-container" v-for="card in statCards" :key="card.title">
        <div class="stat-card">
          <div class="stat-card-face front" :class="card.class">
            <div class="stat-icon">{{ card.icon }}</div>
            <div class="stat-info">
              <h4>{{ card.title }}</h4>
              <p>{{ card.value }}</p>
            </div>
          </div>
          <div class="stat-card-face back" :class="card.class">
            <h4>{{ card.title }}</h4>
            <p>{{ card.description }}</p>
          </div>
        </div>
      </div>
    </div>

    <div class="charts-grid">
      <div class="chart-card">
        <h3>消费构成 (3D)</h3>
        <v-chart class="chart" :option="bar3DChartOption" autoresize />
      </div>
      <div class="chart-card">
        <h3>订单数据云 (3D)</h3>
        <v-chart class="chart" :option="scatter3DChartOption" autoresize />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { GridComponent, LegendComponent, TitleComponent, TooltipComponent, VisualMapComponent } from 'echarts/components';
import VChart from 'vue-echarts';
import 'echarts-gl'; // Import the 3D extension
import { getQuan } from '@/api/user';

use([
  CanvasRenderer,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  VisualMapComponent,
]);

const props = defineProps({
  orderCount: { type: Number, default: 0 },
  totalSpending: { type: Number, default: 0 },
  favoriteCount: { type: Number, default: 0 },
  orders: { type: Array as () => any[], default: () => [] },
  consumption: { type: Number, default: 0 },
  count: { type: Number, default: 0 }
});

const couponCount = ref(0)
onMounted(async () => {
  try {
    const res = await getQuan({ pageNum: 1, pageSize: 100 })
    if (res && (res.total !== undefined || (res.data && res.data.total !== undefined))) {
      couponCount.value = res.total ?? (res.data ? res.data.total : 0)
    }
  } catch (e) {
    couponCount.value = 0
  }
})

// --- Stat Cards Data ---
const statCards = computed(() => [
  { title: '总订单数', value: props.count || props.orderCount, icon: '📦', class: 'orders', description: '历史累计订单数量' },
  { title: '总消费', value: `¥${(props.consumption || props.totalSpending).toFixed(2)}`, icon: '💰', class: 'spending', description: '所有订单的总金额' },
  { title: '优惠券', value: couponCount.value, icon: '🎟️', class: 'coupons', description: '当前可用的优惠券' },
  // { title: '收藏商品', value: props.favoriteCount, icon: '⭐', class: 'favorites', description: '您收藏的商品总数' },
]);


// --- 3D Bar Chart for Spending Composition ---
const bar3DChartOption = computed(() => {
  const data = [
    { name: '电子产品', value: [1, 1, props.totalSpending * 0.4] },
    { name: '生活用品', value: [1, 2, props.totalSpending * 0.3] },
    { name: '服饰装扮', value: [2, 1, props.totalSpending * 0.2] },
    { name: '其他', value: [2, 2, props.totalSpending * 0.1] },
  ].map(item => ({
      name: item.name,
      value: [item.value[0], item.value[1], Math.max(item.value[2], 1)], // Ensure value is not 0 for visibility
      itemStyle: {
        color: `hsl(${Math.random() * 360}, 80%, 60%)`,
      }
  }));

  return {
    tooltip: {},
    visualMap: {
      max: props.totalSpending,
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    xAxis3D: { type: 'category' },
    yAxis3D: { type: 'category' },
    zAxis3D: { type: 'value' },
    grid3D: {
      boxWidth: 200,
      boxDepth: 80,
      viewControl: {
        autoRotate: true
      },
      light: {
        main: {
          intensity: 1.2,
          shadow: true
        },
        ambient: {
          intensity: 0.3
        }
      }
    },
    series: [{
      type: 'bar3D',
      data: data,
      shading: 'lambert',
      label: {
        show: false,
      },
      emphasis: {
        label: {
          show: true,
          textStyle: {
            fontSize: '16',
            color: '#fff',
            backgroundColor: 'rgba(0,0,0,0.5)',
            padding: 5
          }
        }
      }
    }]
  };
});


// --- 3D Scatter Plot for Orders ---
const scatter3DChartOption = computed(() => {
    const data = props.orders.map((order, index) => {
        const date = new Date(order.createTime);
        return [
            date.getTime(), // x: time
            order.amount,      // y: amount
            props.orders.length - index, // z: order sequence
            order.amount // for visualMap
        ];
    });

    return {
        tooltip: {},
        visualMap: {
            min: 0,
            max: Math.max(...props.orders.map(o => o.amount)),
            inRange: {
                color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026'],
                symbolSize: [5, 25]
            }
        },
        xAxis3D: { type: 'value', name: '时间' },
        yAxis3D: { type: 'value', name: '金额' },
        zAxis3D: { type: 'value', name: '序号' },
        grid3D: {
            viewControl: {
                projection: 'perspective',
                autoRotate: true
            }
        },
        series: [{
            type: 'scatter3D',
            data: data,
            symbolSize: 12,
            itemStyle: {
                borderWidth: 1,
                borderColor: 'rgba(255,255,255,0.8)'
            },
            emphasis: {
                itemStyle: {
                    color: '#fff'
                }
            }
        }]
    };
});

</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  border-radius: 15px;
  color: #e2e8f0;
  background-color: #222;
  background-image:
    /* Reflective Sheen */
    linear-gradient(to bottom, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0) 50%),
    /* Carbon Fiber Pattern */
    linear-gradient(45deg, rgba(0, 0, 0, 0.5) 25%, transparent 25%, transparent 75%, rgba(0, 0, 0, 0.5) 75%),
    linear-gradient(-45deg, rgba(0, 0, 0, 0.5) 25%, transparent 25%, transparent 75%, rgba(0, 0, 0, 0.5) 75%);
  background-size: 10px 10px;
  box-shadow: 0 20px 40px rgba(0,0,0,0.5), inset 0 0 15px rgba(0,0,0,0.5);
  width:100%;
}

.dashboard-header h2 {
  font-size: 24px;
  font-weight: 700;
  margin-bottom: 20px;
  color: #ffffff;
  text-align: center;
  text-transform: uppercase;
  letter-spacing: 2px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 30px;
  margin-bottom: 30px;
  perspective: 1000px;
}

.stat-card-container {
  height: 120px;
}

.stat-card {
  width: 100%;
  height: 100%;
  position: relative;
  transform-style: preserve-3d;
  transition: transform 0.8s;
  cursor: pointer;
}

.stat-card-container:hover .stat-card {
  transform: rotateY(180deg);
}

.stat-card-face {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  border-radius: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 20px;
  box-shadow: 0 10px 25px rgba(0,0,0,0.3);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.stat-card-face.front {
  flex-direction: row;
  justify-content: flex-start;
  gap: 20px;
}

.stat-card-face.back {
  transform: rotateY(180deg);
  text-align: center;
}

.stat-card-face.back h4 { margin-top: 0; }
.stat-card-face.back p { font-size: 14px; color: #cbd5e1; }


.orders { background: linear-gradient(135deg, #2563eb, #59a3ff); }
.spending { background: linear-gradient(135deg, #059669, #10b981); }
.coupons { background: linear-gradient(135deg, #d97706, #f97316); }
.favorites { background: linear-gradient(135deg, #7c3aed, #9a6aff); }

.stat-icon { font-size: 38px; }
.stat-info h4 { font-size: 14px; margin: 0 0 5px; color: #cbd5e1; text-transform: uppercase; }
.stat-info p { font-size: 26px; margin: 0; font-weight: 700; color: #fff; }

.charts-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.chart-card {
  background-color: rgba(30, 41, 59, 0.5);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 15px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
}

.chart-card h3 {
  margin: 0 0 15px;
  color: #e2e8f0;
  font-size: 18px;
  font-weight: 600;
  text-align: center;
}

.chart {
  height: 350px;
}

@media (max-width: 992px) {
  .charts-grid {
    grid-template-columns: 1fr;
  }
}
</style>
